<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once "objetos/Usuario.php";
require_once "server/EmailServer.php";

$destinatario = $_POST["destinatario"];
$assunto = $_POST["assunto"];
$conteudo = $_POST["conteudo"];

session_start();
if (!array_key_exists("userId", $_SESSION) && $_SESSION["userId"] == NULL) {
    header("Location: ../index.php");
}
$userId = $_SESSION["userId"];
$emailServer = new EmailServer();

$conn = $emailServer->imapOpen($userId->getLogin(), $userId->getSenha());

$headers = "From: ".$userId->getLogin()."\n";

$enviado = imap_mail($destinatario, $assunto, $conteudo,$headers);
  
$emailServer->imapClose($conn);
if($enviado){
    $connOutbox = $emailServer->imapOpenOutbox($userId->getLogin(), $userId->getSenha());
    $message = "From: ".$userId->getLogin()."\r\n"
               ."To: ".$destinatario."\r\n"
               ."Subject: ".$assunto."\r\n"
               ."\r\n"
               .$conteudo."\r\n";
    $resposta = imap_append($connOutbox, "{127.0.0.1}SENT", $message);
    $emailServer->imapClose($connOutbox);
    header("Location: ../paginas/novoEmail.php?enviado=1");
}else{
    header("Location: ../paginas/novoEmail.php?errenviado=1");
}

?>
